import axios from 'axios'
import { ElLoading,ElMessage  } from 'element-plus'
import { wmsStore } from '@/store/pinia'

let store = wmsStore()

let loading:any;
class Http {
    myAxios: any;
    constructor(config: any) {
        this.myAxios = axios.create(config);
   
        this.myAxios.interceptors.request.use(function (config:any) {
            loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            if (store.token != "") {
                config.headers.token = store.token
            }
           return config;

        }, function (error:any) {
            loading.close()
            return Promise.reject(error);

        });

        this.myAxios.interceptors.response.use(function (response:any) { 
            loading.close()
            const { code, message, data } = response.data

            if (code === 0) {
                return data
            } else if (code == undefined) {
                return response
            } else {
                ElMessage.error(message)
                return Promise.reject(message)
            }

        }, function (error:any) {
            loading.close()
            return Promise.reject(error);
        
       
        });
    }
    
    //url:/api/product   params:{id:1,category:3}
    //  /api/product?id=1&category=3
    get<T>(url: string, params={}): Promise<any> {
        return this.myAxios.get(url, {params});
    }

    // { name:小米su7,category:3 }
    post<T>(url: string,data = {}): Promise<any> {
        return this.myAxios.post(url, data);
    }

    put<T>(url: string, data = {}): Promise<any> {
        return this.myAxios.put(url, data);
    }

    delete<T>(url: string, params={}): Promise<any> {
        return this.myAxios.delete(url, { params});
    }

}
const config = {
    baseURL: '',
    timeout: 30 * 1000,
    withCredentials: true,
}

export default new Http(config);
 